import re
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt  # 数学绘图库
import jieba  # 分词库
from wordcloud import WordCloud, ImageColorGenerator  # 词云库
from PIL import Image
import numpy as np


comments = ''
with open('./comment.txt', 'r', encoding='utf-8') as f:
    comments = f.read()
comments = re.sub('[^a-zA-Z0-9\u4e00-\u9fa5]', '', comments)
# count = {}
# for word in jieba.cut(comments):
#     count[word]=count.get(word,0)+1
# words = list(count.items())
# words.sort(key=lambda x:x[1], reverse=True)
# for key, word in words:
#     print("%s---->%s" % (key, word))
# exit()
# 停用词
no_name = ["的", "了", '是', '我', '都', '就', '不', '有', '也', '和', '还', '就是', '在', '还是', '就是', '其他', '没有']

desc_result = "/".join(jieba.cut(comments))  # 只有用"/"或" "等分割开的，才能用于构建词云图

# 初始化自定义背景图片
bg_img = "./1.jpg"
image = Image.open(bg_img)
graph = np.array(image)

# wordcloud配置
wc = WordCloud(
    font_path="C:\Windows\Fonts\msyhbd.ttc",  # 设置字体
    background_color='white',  # 背景颜色
    width=image.size[0],  # 设置宽，我这里设置和背景图片宽一样
    height=image.size[1],  # 设置高，我这里设置和背景图片高一样
    max_font_size=70, min_font_size=10,  # 字体最大/最小值
    stopwords=no_name,  # 设置停用词，不在词云图中显示
    max_words=2000,  # 设置最大显示的字数
    mode='RGBA'
)
wc.generate(desc_result)
# 绘制文字的颜色以背景图颜色为参考
image_color = ImageColorGenerator(graph)  # 从背景图片生成颜色值
wc.recolor(color_func=image_color)


img_name = 'desc_wc.png'   # 保存图片的名字
# 生成图片
wc.to_file(img_name)
# 4、显示图片
plt.figure("词云图")  # 指定所绘图名称
plt.imshow(wc)       # 以图片的形式显示词云
plt.axis("off")      # 关闭图像坐标系
plt.show()
